import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QPushButton
from PyQt5.QtGui import QPainter, QImage, QPixmap
from PyQt5.QtCore import Qt
import SimpleITK as sitk
import numpy as np


 
class ImageWidget(QWidget):
    def __init__(self, parent=None):
        super(ImageWidget, self).__init__(parent)
        self.image = QImage()
        self.image_loaded = False
 
    def load_image(self, image_path):
        labelImage = sitk.ReadImage("/media/chyang/data/dataset/project/hipbone/nnUNet_raw/Dataset001_PelvicNAS/imagesTr/1.3.6.1.4.1.9328.50.4.0001_0000.nii.gz") #in_file是nii.gz文件的路径
        img = sitk.GetArrayFromImage(labelImage)
        img_scaled = (img - img.min()) / (img.max() - img.min()) * 255
        img_scaled = img_scaled.astype(np.uint8)
        slice = img_scaled[:, :, 200].copy()
        width = slice.shape[0]
        height = slice.shape[1]
        format = QImage.Format_Grayscale8
        if slice.ndim == 3:
            format = QImage.Format_RGB8
        self.image = QImage(slice.data, height, width, height, format) #
        self.image_loaded = True
        self.update()  # Trigger repaint
 
    def paintEvent(self, event):
        if self.image_loaded:
            painter = QPainter(self)
            painter.drawImage(self.rect(), self.image)
 
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.init_ui()
 
    def init_ui(self):
        self.widget = ImageWidget(self)
        self.setCentralWidget(self.widget)
 
        self.btn_load_image = QPushButton('Load Image', self)
        self.btn_load_image.clicked.connect(self.load_image)
 
        self.main_layout = self.layout()
        self.main_layout.addWidget(self.btn_load_image)
 
    def load_image(self):
        image_path = '/media/chyang/data/dataset/detect/MixFormer/lasot/airplane/airplane-1/img/00000001.jpg'  # Replace with your image path
        self.widget.load_image(image_path)
 
if __name__ == '__main__':    
    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())